﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

public partial class Boundary_FrmProject : System.Web.UI.Page
{
    private string profile = "";
    private string role = "";

    private CtrlProject ctrlProject
    {
        get
        {
            return (CtrlProject)(Session["ctrlProject"]);
        }
        set
        {
            (Session["ctrlProject"]) = value;
        }
    }

    private string changing
    {
        get
        {
            return (string)(ViewState["changing"]);
        }
        set
        {
            ViewState["changing"] = value;
        }
    }

    System.IFormatProvider format = new System.Globalization.CultureInfo("es-ES", true);

    protected void Page_Load(object sender, EventArgs e)
    {
        consultando.Visible = false;
        modificando.Visible = false;
        ninguno.Visible = true;
        insertando.Visible = false;

        Type blo = txtDescription.GetType();
        Type bla = txtName.GetType();

        // Redirection if there is no cookie.
        HttpCookie cookie = Request.Cookies.Get("requmanaLogin");
        if (cookie == null)
        {
            Response.Redirect("FrmLogin.aspx");
        }
        else
        {
            profile = cookie.Values[3];
            role = cookie.Values[4];
        }

        // Inicializa control de proyecto
        if (Session["ctrlProject"] == null)
        {
            ctrlProject = new CtrlProject();
        }

        // Carga y configura el ctlGridView
        if (Int32.Parse(cookie.Values[3]) == 0)
        {
            ctlGridView.setDataSource(ctrlProject.getData());
        }
        else
        {
            ctlGridView.setDataSource(ctrlProject.getDataC(Int32.Parse(cookie.Values[5])));
        }

        ctlGridView.Select += new MyEventHandler(ctlGridView_Select);
        ctlGridView.Modify += new MyEventHandler(ctlGridView_Modify);
        ctlGridView.Eliminate += new MyEventHandler(ctlGridView_Eliminate);

        // Configura el
        ctlMembers.Allocate += new MyEventHandlerCtlMembers(ctlMembers_Allocate);
        ctlMembers.Deallocate += new MyEventHandlerCtlMembers(ctlMembers_Deallocate);

        // Desabilita campos
        if (!(IsPostBack))
        {
            disableFields();
        }
    }

    void ctlMembers_Deallocate(object sender, int iValue)
    {
        ctrlProject.deallocateMember(iValue);
    }

    void ctlMembers_Allocate(object sender, int iValue)
    {
        ctrlProject.allocateMember(iValue);
    }

    private bool validateFields()
    {
        bool valid = true;
        bool validDate = true;
        
        hideValidations();

        Regex name = new Regex("^(.{1,50})$");
        Regex description = new Regex("^(.*)$");
        Regex duration = new Regex("^((\\d+(\\.\\d+)?)?)$");
        Regex objectives = new Regex("^(.{0,50})$");

        DateTime temp = new DateTime();

        System.IFormatProvider format = new System.Globalization.CultureInfo("es-ES", true);

        if (txtName.Text == "")
        {
            nameValidation.Visible = true;
            nameValComment.Visible = true;
            valid = false;
        }
        else 
        {
            if (!(name.IsMatch(txtName.Text)))
            {
                nameValidation.Visible = true;
                nameValFormat.Visible = true;
                valid = false;
            }
        }
        if (!(duration.IsMatch(txtDuration.Text)))
        {
            durationValidation.Visible = true;
            durationValFormat.Visible = true;
            valid = false;
        }
        if (txtBegin.Text == "")
        {
            beginValidation.Visible = true;
            beginValComment.Visible = true;
            valid = false;
        }
        else
        {
            if (!(DateTime.TryParse(txtBegin.Text, format, System.Globalization.DateTimeStyles.None, out temp)))
            {
                beginValidation.Visible = true;
                beginValFormat.Visible = true;
                valid = false;
            }
        }

        if (txtEnd.Text == "")
        {
            endValidation.Visible = true;
            endValComment2.Visible = true;
            valid = false;
            validDate = false;
        }
        else
        {            
            DateTime begin = new DateTime();
            DateTime end = new DateTime();

            if (txtBegin.Text == "")
            {
                validDate = false;
                beginValidation.Visible = true;
                beginValComment.Visible = true;
                valid = false;
            }
            else
            {
                if (DateTime.TryParse(txtBegin.Text, format, System.Globalization.DateTimeStyles.None, out temp))
                {
                    begin = DateTime.Parse(txtBegin.Text, format);
                }
                else
                {
                    validDate = false;
                    beginValidation.Visible = true;
                    beginValFormat.Visible = true;
                    valid = false;
                }
            }

            if (DateTime.TryParse(txtEnd.Text, format, System.Globalization.DateTimeStyles.None, out temp))
            {
                end = DateTime.Parse(txtEnd.Text, format);
            }
            else
            {
                validDate = false;
                endValidation.Visible = true;
                endValFormat.Visible = true;
                valid = false;
            }

            if (validDate)
            {
                int difference = DateTime.Compare(end, begin);
                if (difference <= 0)
                {
                    endValidation.Visible = true;
                    endValComment.Visible = true;
                    valid = false;
                }
            }
            else
            {
                valid = false;
            }
        }

        if (!(objectives.IsMatch(txtObjectives.Text)))
        {
            objectivesValidation.Visible = true;
            objectivesValFormat.Visible = true;
            valid = false;
        }

        return valid;
    }

    private void hideValidations()
    {
        nameValidation.Visible = false;
        nameValComment.Visible = false;
        nameValFormat.Visible = false;
        durationValidation.Visible = false;
        durationValComment.Visible = false;
        durationValFormat.Visible = false;
        beginValidation.Visible = false;
        beginValComment.Visible = false;
        beginValFormat.Visible = false;
        endValidation.Visible = false;
        endValComment.Visible = false;
        endValFormat.Visible = false;
        endValComment2.Visible = false;
        objectivesValidation.Visible = false;
        objectivesValFormat.Visible = false;
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        bool admin = (profile == "0");

        consultando.Visible = false;
        modificando.Visible = false;
        ninguno.Visible = false;
        insertando.Visible = true;

        if (admin)
        {
            clearFields();
            changing = "inserting";
            enableFields();
            ctlMessage1.showMessage("info", "Puede digitar la informacion del proyecto.");
        }

        ctlGridView.hideButtons();
        ctlMembers.showButtons();
    }

    protected void ctlGridView_Select(object sender, int iVal)
    {
        consultando.Visible = true;
        modificando.Visible = false;
        ninguno.Visible = false;
        insertando.Visible = false;

        loadFields(ctrlProject.getProject(iVal));
        disableFields();

        ctlMembers.hideButtons();
    }

    protected void ctlGridView_Modify(object sender, int iVal)
    {
        bool admin = (profile == "0");
        bool leader = (role == "0");

        consultando.Visible = false;
        modificando.Visible = true;
        ninguno.Visible = false;
        insertando.Visible = false;

        if (admin || leader)
        {
            loadFields(ctrlProject.getProject(iVal));
            changing = "modifying";
            enableFields();
            ctlMessage1.showMessage("info", "Puede editar la informacion del proyecto.");
        }

        ctlGridView.hideButtons();
        ctlMembers.showButtons();
    }

    protected void ctlGridView_Eliminate(object sender, int iVal)
    {
        bool admin = (profile == "0");

        if (admin)
        {
            ctrlProject.deleteProject(iVal);
            ctlMessage2.showMessage("success", "El Proyecto ha sido eliminado satisfactoriamente.");
            Response.Redirect("FrmProject.aspx");
        }
    }

    private void loadFields(Project project)
    {
        txtName.Text = project.sName;
        txtBegin.Text = (project.dStartingDate).ToString(format);
        txtEnd.Text = (project.dCompletionDate).ToString(format);
        txtDuration.Text = (project.fEstimatedDuration).ToString();
        txtObjectives.Text = project.sObjectives;
        txtDescription.Text = project.sDescription;

        ctlMembers.clearMembers();
        
        for (int i = 0; i < project.lResources.Count; i++)
        {
            ctlMembers.loadMembers((project.lResources[i].iId).ToString(), project.lResources[i].sFirstName);
        }

        ctlMembers.DataBind();
         
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {

        consultando.Visible = false;
        modificando.Visible = false;
        ninguno.Visible = true;
        insertando.Visible = false;

        if (validateFields())
        {
            if (changing.Equals("modifying"))
            {
                ctrlProject.setProject(txtName.Text, txtDescription.Text, DateTime.Parse(txtBegin.Text, format), DateTime.Parse(txtEnd.Text, format), float.Parse(txtDuration.Text), txtObjectives.Text);
                ctlMessage1.showMessage("success", "El Proyecto ha sido modificado satisfactoriamente.");
                Response.Redirect("FrmProject.aspx");
            }

            if (changing.Equals("inserting"))
            {
                    ctrlProject.addProject(txtName.Text, txtDescription.Text, DateTime.Parse(txtBegin.Text, format), DateTime.Parse(txtEnd.Text, format), float.Parse(txtDuration.Text), txtObjectives.Text);
                    ctlMessage1.showMessage("success", "El Proyecto ha sido agregado satisfactoriamente.");
                    Response.Redirect("FrmProject.aspx");
            }

            changing = "";
            //clearFields();
            disableFields();
            ctlGridView.update();
        }

        ctlGridView.showButtons();
    }

    protected void btnCancelar_Click(object sender, EventArgs e)
    {
        insertando.Visible = false;
        modificando.Visible = false;
        consultando.Visible = false;
        ninguno.Visible = true;

        changing = "";
        clearFields();
        disableFields();

        ctlGridView.showButtons();
    }

    public void clearFields()
    {
        txtBegin.Text = "";
        txtDescription.Text = "";
        txtEnd.Text = "";
        txtDuration.Text = "";
        txtName.Text = "";
        txtObjectives.Text = "";
    }

    public void enableFields()
    {
        txtBegin.Enabled = true;
        txtBegin_CalendarExtender.Enabled = true;
        txtDescription.Enabled = true;
        txtEnd.Enabled = true;
        txtEnd_CalendarExtender.Enabled = true;
        txtDuration.Enabled = true;
        txtName.Enabled = true;
        txtObjectives.Enabled = true;
        btnSave.Enabled = true;
        btnCancelar.Enabled = true;
        ctlMembers.Enabled = true;
    }

    public void disableFields()
    {
        
        txtBegin.Enabled = false;
        txtBegin_CalendarExtender.Enabled = false;
        txtDescription.Enabled = false;
        txtEnd.Enabled = false;
        txtEnd_CalendarExtender.Enabled = false;
        txtDuration.Enabled = false;
        txtName.Enabled = false;
        txtObjectives.Enabled = false;
        btnSave.Enabled = false;
        btnCancelar.Enabled = false;
        ctlMembers.Enabled = false;
    }
}
